<?php
/**
 * File: Address.php
 * User: Mr.Yang
 * Date: 2025/3/29 0029
 * Time: 9:43
 * Note:
 */

namespace app\admin\model;


use think\Model;

class Address extends Model
{
    protected $autoWriteTimestamp = "datetime";
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $createTime = "date_entered";
    protected $updateTime = "update_entered";

    public static function init()
    {
        self::event("before_delete", function ($query){

            return true;
        });

        self::event('before_insert', function ($query){
            //判断是否为首次添加
            $count = Address::where([['userid', '=', $query->userid],['id_default', '=', 1]])->count();
            if ($count == 0) {
                $query->is_default = 1;
            }
            return true;
        });
    }

    /**
     * @param int $offset
     * @param int $limit
     * @param array $where
     * @return array
     */
    public function getList($offset = 0, $limit=10, $where = [])
    {
        return $this->alias('b')->field('b.*, c.catname')
            ->leftJoin('category c', 'c.id=b.catid')
            ->where($where)
            ->limit($offset, $limit)
            ->order('b.id', 'desc')
            ->select()
            ->toArray();
    }

    /**
     * @param array $where
     * @return $this
     */
    public function getListCount($where = [])
    {
        return $this->alias('b')->where($where)->count();
    }

    /**
     * @param $id
     * @return array
     */
    public function getOneById($id)
    {
        return $this->where("id", $id)->findOrEmpty()->toArray();
    }

    /**
     * @param $data
     * @return bool
     */
    public function add($data)
    {
        return $this->save($data);
    }

    /**
     * @param $id
     * @param $data
     * @return bool
     */
    public function edit($id, $data)
    {
        return $this->save($data, [['id', '=', $id]]);
    }

    /**
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function del($id)
    {
        return self::get($id)->delete();
    }

    public function getAll()
    {
        return $this->selectOrFail();
    }
}